﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using WindowsLive;
using Microsoft.WindowsAzure;
using FeedReader.Shared.Data;
using Microsoft.WindowsAzure.ServiceRuntime;

namespace MvcFrontEnd.Controllers
{
    public class WindowsLiveController : Controller
    {
        public ActionResult Handle()
        {
            CloudStorageAccount acc = CloudStorageAccount.FromConfigurationSetting("DataConnectionString");
            LogDataSource log = new LogDataSource(acc);

            log.Insert("Authentication", "Handleing redirect", "Information", DateTime.Now);

            string action = Request.Params["action"];
            var wll = new WindowsLiveLogin(RoleEnvironment.GetConfigurationSettingValue("wll_appid"), RoleEnvironment.GetConfigurationSettingValue("wll_secret"));
            if (action == "logout")
            {
                log.Insert("Authentication", "Logging out", "Information", DateTime.Now);

                HttpCookie loginCookie = new HttpCookie("webauthtoken");
                loginCookie.Expires = DateTime.Now.AddYears(-10);
                Response.Cookies.Add(loginCookie);

                return RedirectToAction("index", "home");
            }
            else if (action == "clearcookie")
            {
                log.Insert("Authentication", "Clearing cookies", "Information", DateTime.Now);
                HttpCookie loginCookie = new HttpCookie("webauthtoken");
                loginCookie.Expires = DateTime.Now.AddYears(-10);
                Response.Cookies.Add(loginCookie);

                string type;
                byte[] content;
                wll.GetClearCookieResponse(out type, out content);
                return new FileContentResult(content, type);
            }
            else
            {
                log.Insert("Authentication", "Logging in", "Information", DateTime.Now);
                WindowsLiveLogin.User user = wll.ProcessLogin(Request.Form);
                HttpCookie loginCookie = new HttpCookie("webauthtoken");
                if (user != null)
                {
                    loginCookie.Value = user.Token;

                    if (user.UsePersistentCookie)
                    {
                        loginCookie.Expires = DateTime.Now.AddYears(10);
                        log.Insert("Authentication", "Logging user " + user.Id, "Information", DateTime.Now);
                    }
                }
                else
                {
                    loginCookie.Expires = DateTime.Now.AddYears(-10);
                }
                Response.Cookies.Add(loginCookie);
                return RedirectToAction("Index", "Home");
            }
        }

    }
}
